<template>
  <el-dialog class="public-dialog" title="批量上传二手机维修编号" width="90%" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div style="height: 80vh">
      <el-form :model="formInline" ref="formRef">
        <el-table :data="formInline.tableData" border class="w-[100%] h-[750px]" :span-method="objectSpanMethod">
          <el-table-column prop="orderIndex" label="序号" width="50" />
          <el-table-column width="180">
            <template #header>
              <div>平台/站点</div>
              <div>店铺</div>
            </template>
            <template #default="{ row }">
              <VText :value="row.platform + '/' + row.site" />
              <VText :value="row.shop" />
            </template>
          </el-table-column>
          <el-table-column prop="name" width="180">
            <template #header>
              <div>系统订单号</div>
              <div>平台订单号</div>
            </template>
            <template #default="{ row }">
              <VText :value="row.order_sn" />
              <VText :value="row.platform_order_sn" />
            </template>
          </el-table-column>

          <el-table-column label="图片" width="110">
            <template #default="{ row }">
              <el-image class="w-[74px] h-[74px] mr-[4px]" style="border: 0.5px solid #f0f0f0; border-radius: 4px" :src="row.main_img" fit="fill" />
            </template>
          </el-table-column>
          <el-table-column prop="name" width="180">
            <template #header>
              <div>系统SKU</div>
              <div>自定义SKU</div>
            </template>
            <template #default="{ row }">
              <VText :value="row.platform_sku" />
              <VText :value="row.asin" />
            </template>
          </el-table-column>

          <el-table-column prop="name" label="维修编号" width="180">
            <template #default="{ row, $index }">
              <div v-for="idx in row.quantity" :key="idx">
                <el-form-item :prop="`tableData.${$index}.repair_number.${idx - 1}`" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]">
                  <el-input v-model="row.repair_number[idx - 1]" oninput="value=value.replace(/[^A-Za-z0-9]/g, '')" class="w-[100%]" placeholder="维修编号" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="order_status_desc" label="订单状态" width="100" />
          <el-table-column prop="sku_cn_title" label="商品名称" minWidth="160">
            <template #default="{ row }">
              <VText :value="row.sku_cn_title" :line="3" />
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="available_stock" label="可用库存" width="100" />

          <el-table-column label="操作" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="resetRow(row)"> 重置 </el-button>
              <el-button link type="danger" @click="delRow(row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose(false)" :disabled="loading"> 取消 </el-button>
      <el-button type="primary" @click="save" :loading="loading"> 确认 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"

import api from "../../api"
const modelValue = ref(false)
const props = defineProps({})
const emit = defineEmits(["refresh"])
const formRef = ref()
const formInline = ref({
  tableData: [],
})

const loading = ref(false)

const handleClose = (refresh) => {
  modelValue.value = false
  nextTick(() => {
    formInline.value.tableData = []
    if (refresh) emit("refresh")
  })
}
function hasDuplicateField(array, field) {
  const values = array.map((obj) => obj[field]).flat()
  return values.findIndex((value, index) => values.indexOf(value) !== index)
}
const save = async () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let index = hasDuplicateField(formInline.value.tableData, "repair_number")
      if (index != -1) {
        return ElMessage({ message: `第${index}条数据 维修编号 存在重复！`, type: "warning", duration: 30000, showClose: true })
      }

      let params = {
        handler: "order_sku_repair_number",
        data: formInline.value.tableData.map((v) => ({ item_id: v.id, repair_number: v.repair_number })),
      }
      api.batchOperation(params).then((res) => {
        ElMessage.success("批量操作成功！")
        handleClose()
      })
    } else {
      console.log("error submit!")
    }
  })
}

// 重置订单
const resetRow = (row) => {
  formInline.value.tableData.forEach((item) => {
    if (item.order_sn == row.order_sn) {
      item.repair_number = Array(item.quantity)
    }
  })
}
// 删除订单
const delRow = (row) => {
  formInline.value.tableData = formInline.value.tableData.filter((v) => v.order_sn != row.order_sn)
}

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex < 3 || columnIndex == 10) {
    if (row.rowIndex == 0) {
      return { rowspan: row.orderLength, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
}
const queryList = async (list = []) => {
  let data = []
  list.forEach((v, idx) => {
    v.items.forEach((x, i) => {
      data.push({
        ...x,
        platform: v.platform,
        site: v.site,
        shop: v.shop,
        order_sn: v.order_sn,
        platform_order_sn: v.platform_order_sn,
        order_status_desc: v.order_status_desc,
        repair_number: x?.repair_number.length ? x.repair_number : Array(v.quantity),
        // 自定义参数
        // order_id: v.id,
        // shop_id: v.shop_id,
        // recipient_country: v.recipient.recipient_country,
        orderLength: v.items.length,
        rowIndex: i,
        orderIndex: idx + 1,
      })
    })
  })
  formInline.value.tableData = data
  return { data, total: 0 }
}

const open = (rows) => {
  modelValue.value = true
  nextTick(() => {
    queryList(rows)
  })
}
defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
